package com.hliushi.netty.server.handler;

import com.hliushi.netty.message.LoginRequestMessage;
import com.hliushi.netty.message.LoginResponseMessage;
import com.hliushi.netty.server.service.UserService;
import com.hliushi.netty.server.service.UserServiceFactory;
import com.hliushi.netty.server.session.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author llhuang10
 * @date 2021/10/22 10:14
 */
@ChannelHandler.Sharable
public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
        LoginResponseMessage response;
        if (msg == null) {
            response = new LoginResponseMessage(false, "msg请求体为空!");
            ctx.writeAndFlush(response);
            return;
        }

        String username = msg.getUsername();
        String password = msg.getPassword();
        UserService userService = UserServiceFactory.getUserService();
        boolean res = userService.login(username, password);
        if (res) {
            // 登录成功后, 就使用SessionFactory.getSession.bind(channel, username), 将channel和username进行绑定
            // 绑定的底层就是使用了  一个HashMap来维护 channel 和 username的 key/value对应关系
            SessionFactory.getSession().bind(ctx.channel(), username);
            response = new LoginResponseMessage(true, "登录成功");
        } else {
            response = new LoginResponseMessage(false, "用户名或密码错误!");
        }
        ctx.writeAndFlush(response);
    }
}
